package com.srmt.document.examples;

import com.srmt.document.api.DocumentService;
import com.srmt.document.api.DocumentManager;
import com.srmt.document.factory.DocumentServiceFactory;
import com.srmt.document.model.PermissionSetting;
import com.srmt.user.api.UserIdResolver;
import com.srmt.user.factory.UserIdResolverFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文档权限刷新功能示例
 * 
 * 演示如何使用refreshPermissions API来清空并重新设置文档权限
 * 
 * @author SRMT Development Team
 * @since 1.5.0
 */
public class RefreshPermissionsExample {
    
    private static final Logger logger = LoggerFactory.getLogger(RefreshPermissionsExample.class);
    
    public static void main(String[] args) {
        try {
            // 1. 创建服务实例
            DocumentService documentService = DocumentServiceFactory.createDefault();
            DocumentManager documentManager = documentService.getDocumentManager();
            UserIdResolver userResolver = UserIdResolverFactory.createDefault();
            
            // 2. 创建或使用已有文档
            String folderToken = System.getenv("FEISHU_DEFAULT_FOLDER_TOKEN");
            String docId = documentManager.createBlankDocument("权限刷新示例文档", folderToken);
            logger.info("创建文档成功: {}", docId);
            
            // 3. 获取用户ID（通过电话号码）
            String userId1 = userResolver.getUserIdByPhone("+86-13800138000");
            String userId2 = userResolver.getUserIdByPhone("+86-13900139000");
            String userId3 = userResolver.getUserIdByPhone("+86-13700137000");
            
            // 4. 设置初始权限
            logger.info("设置初始权限...");
            PermissionSetting initialPermission = PermissionSetting.builder()
                    .addReadUser(userId1)
                    .addWriteUser(userId2)
                    .addAdminUser(userId3)
                    .needNotification(false)
                    .build();
            
            documentManager.setPermissions(docId, initialPermission);
            logger.info("初始权限设置完成");
            
            // 5. 等待一段时间后刷新权限
            Thread.sleep(2000);
            
            // 6. 刷新权限 - 清空所有旧权限并设置新权限
            logger.info("刷新文档权限...");
            PermissionSetting newPermission = PermissionSetting.builder()
                    .addWriteUser(userId1)  // userId1从只读升级为编辑
                    .addReadUser(userId3)   // userId3从管理员降级为只读
                    // userId2的权限被完全移除
                    .needNotification(false)
                    .build();
            
            documentManager.refreshPermissions(docId, newPermission);
            logger.info("权限刷新成功!");
            
            // 7. 验证结果
            logger.info("权限刷新完成，新的权限设置：");
            logger.info("- {} 现在有编辑权限（之前是只读）", userId1);
            logger.info("- {} 现在有只读权限（之前是管理员）", userId3);
            logger.info("- {} 的权限已被移除（之前是编辑）", userId2);
            
            // 8. 演示清空所有权限（只保留owner）
            Thread.sleep(2000);
            logger.info("清空所有权限（除了owner）...");
            
            PermissionSetting emptyPermission = PermissionSetting.builder()
                    .needNotification(false)
                    .build();
            
            documentManager.refreshPermissions(docId, emptyPermission);
            logger.info("成功清空所有权限，现在只有文档owner可以访问");
            
        } catch (Exception e) {
            logger.error("权限刷新示例执行失败", e);
        }
    }
    
    /**
     * 演示批量权限刷新
     */
    public static void batchRefreshExample(DocumentManager documentManager) throws Exception {
        String docId = "your_document_id";
        
        // 构建包含多个用户的权限设置
        PermissionSetting.Builder builder = PermissionSetting.builder();
        
        // 添加只读用户
        String[] readUsers = {"ou_user1", "ou_user2", "ou_user3"};
        for (String user : readUsers) {
            builder.addReadUser(user);
        }
        
        // 添加编辑用户
        String[] writeUsers = {"ou_user4", "ou_user5"};
        for (String user : writeUsers) {
            builder.addWriteUser(user);
        }
        
        // 添加管理员
        builder.addAdminUser("ou_admin1");
        
        // 设置权限控制
        builder.allowComment(true)
               .allowCopy(false)
               .needNotification(false);
        
        PermissionSetting batchPermission = builder.build();
        
        // 刷新权限
        logger.info("执行批量权限刷新...");
        documentManager.refreshPermissions(docId, batchPermission);
        logger.info("批量权限刷新完成，共设置 {} 个用户权限", 
                   readUsers.length + writeUsers.length + 1);
    }
    
    /**
     * 演示权限降级场景
     */
    public static void downgradePermissionsExample(DocumentManager documentManager) throws Exception {
        String docId = "your_document_id";
        
        // 场景：将所有编辑权限降级为只读权限
        String[] usersToDowngrade = {"ou_editor1", "ou_editor2", "ou_editor3"};
        
        PermissionSetting downgradePermission = PermissionSetting.builder()
                .addReadUsers(usersToDowngrade)  // 全部设为只读
                .needNotification(true)          // 发送通知告知用户权限变更
                .build();
        
        logger.info("执行权限降级...");
        documentManager.refreshPermissions(docId, downgradePermission);
        logger.info("权限降级完成，所有用户现在只有只读权限");
    }
}